package com.guchenbo.example.juc;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {

    static int busCounter = 0;

    public static synchronized void departBus(){
        busCounter++;
    }

    private static String getTime() {
        DateFormat df = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
        return df.format(new Date());
    }

    public static class Passenger implements Runnable {

        public Passenger(CyclicBarrier barrier){
            this.barrier = barrier;
        }

        CyclicBarrier barrier;

        @Override
        public void run() {
            try {
                Random random = new Random();
                Thread.sleep(random.nextInt(10000)); // 到达时间随机
                String arriveTime = getTime();
                int index = barrier.await();
                System.out.println("第" + (5 - index) + "位乘客于" +arriveTime + "到达");
            } catch (BrokenBarrierException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static class BusManager implements Runnable {

        @Override
        public void run() {
            departBus();
            System.out.println("**********************");
            System.out.println("第" + busCounter + "辆大巴于" +getTime() + "发车");
            System.out.println("乘客到达时间如下：");
        }
    }

    public static void main(String[] args) {

        CyclicBarrier barrier = new CyclicBarrier(5, new BusManager());

        ExecutorService pool =Executors.newFixedThreadPool(10);
        for (int i = 0; i < 50; i++) {  //共50名乘客
            pool.submit(new Passenger(barrier));
        }
//        pool.shutdown();
    }

}
